package com.bootdo.jiashan.model;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.core.io.ClassPathResource;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: hje
 * @Description:
 * @Date: 2019/5/19 上午2:51
 */
@Data
public class Area {

    public static List<Area> areaList = new ArrayList<>();

    public static Map<String,Area> areaMap = new HashMap<>();

    private String code;
    private String name;
    private String parentCode;

    public static Map<String,Area> getAreaMap(){
        if(!areaMap.isEmpty()){
            return areaMap;
        }
        initArea();
        return areaMap;
    }

    public static List<Area> getAreaList(){
        if(CollectionUtils.isNotEmpty(areaList)){
            return areaList;
        }
        initArea();
        return areaList;
    }

    private static void initArea(){
        try {
            ClassPathResource classPathResource = new ClassPathResource("area.json");
            InputStream inputStream =classPathResource.getInputStream();
            BufferedReader brname = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            String line;
            StringBuffer s = new StringBuffer();
            while((line = brname.readLine()) != null){
                s.append(line);
            }

            JSONArray jsonArray = JSON.parseArray(s.toString());
            parseArea(jsonArray,null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void parseArea(JSONArray jsonArray, String parentCode){
        if(jsonArray == null || jsonArray.isEmpty())
            return;
        for(int i = 0; i < jsonArray.size(); i++) {
            Area area = new Area();
            JSONObject obj = jsonArray.getJSONObject(i);
            area.setCode((String) obj.get("code"));
            area.setName((String) obj.get("name"));
            area.setParentCode(parentCode);
            areaMap.put(area.getCode(),area);
            areaList.add(area);
            JSONArray jsonArray2 = obj.getJSONArray("children");
            parseArea(jsonArray2,area.getCode());
        }
    }

}
